//举例
var foo = { a: 0, b: { c: 1 } };
var boo =deepClone(foo)
boo.a = 3;
boo.b.c = 4;
console.log(foo);
//结果: { a: 0 , b: { c: 1} }
console.log(boo);
//结果: { a: 3, b: { c: 4 } }




/**
 * @param obj 可以是数组,日期对象,对象,支持嵌套
 */
function deepClone(obj) {
  var copy;
// Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;
// Handle Date
  if (obj instanceof Date) {
    copy = new Date();
copy.setTime(obj.getTime());
return copy;
}

  // Handle Array
  if (obj instanceof Array) {
    copy = [];
for (var i = 0, len = obj.length;
i < len;
i++) {
        copy[i] = deepClone(obj[i]);
}
    return copy;
}

  // Handle Function
  if (obj instanceof Function) {
    copy = function() {
      return obj.apply(this, arguments);
}
    return copy;
}

  // Handle Object
  if (obj instanceof Object) {
      copy = {};
for (var attr in obj) {
          if (obj.hasOwnProperty(attr)) copy[attr] = deepClone(obj[attr]);
}
      return copy;
}

  throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}




//第2种方法，适合api数据
function deepClone(obj, hash = new WeakMap()) {
  if (obj === null) return obj; 
  // 如果是null或者undefined我就不进行拷贝操作
  if (obj instanceof Date) return new Date(obj);
  if (obj instanceof RegExp) return new RegExp(obj);
  // 可能是对象或者普通的值  如果是函数的话是不需要深拷贝
  if (typeof obj !== "object") return obj;
  // 是对象的话就要进行深拷贝
  if (hash.get(obj)) return hash.get(obj);
  let cloneObj = new obj.constructor();
  // 找到的是所属类原型上的constructor,而原型上的 constructor指向的是当前类本身
  hash.set(obj, cloneObj);
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      // 实现一个递归拷贝
      cloneObj[key] = deepClone(obj[key], hash);
    }
  }
  return cloneObj;
}
let obj = { name: 1, address: { x: 100 } };
obj.o = obj; // 对象存在循环引用的情况
let d = deepClone(obj);
obj.address.x = 200;
console.log(d);